#include "Dialog.h"
#include "ui_Dialog.h"
#include <QGridLayout>
#include <QFileDialog>
#include <QProcess>
#include <QDebug>
#include <QtNetwork/QHostAddress>

#include <steam/steam_api.h>
// simple class to marshal callbacks from pinging a game server
    class CGameServerPing : public ISteamMatchmakingPingResponse
    {
    public:
        CGameServerPing()
        {
            m_hGameServerQuery = HSERVERQUERY_INVALID;
        }

        void RetrieveSteamIDFromGameServer( uint32 unIP, uint16 unPort )
        {
            m_hGameServerQuery = SteamMatchmakingServers()->PingServer( unIP, unPort, this );
        }

        void CancelPing()
        {
            m_hGameServerQuery = HSERVERQUERY_INVALID;
        }

        // Server has responded successfully and has updated data
        virtual void ServerResponded( gameserveritem_t &server )
        {
            m_hGameServerQuery = HSERVERQUERY_INVALID;
        }

        // Server failed to respond to the ping request
        virtual void ServerFailedToRespond()
        {
            m_hGameServerQuery = HSERVERQUERY_INVALID;
        }

    private:
        HServerQuery m_hGameServerQuery;	// we're ping a game server, so we can convert IP:Port to a steamID
    };
//#include "CGameServerPing.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    this->resize(800, 500);
    // 参数
    m_qstrArguments.push_back("-game left4dead2");
    m_qstrArguments.push_back("-port 27015");
    m_qstrArguments.push_back("+sv_pure 0");
    m_qstrArguments.push_back("-console");
    m_qstrArguments.push_back("-novid");
    m_qstrPlayerName = "[Yd]路人甲";

    // ip
    m_pTcpSocket = new QTcpSocket(this);    
    connect(m_pTcpSocket, SIGNAL(connected()), this, SLOT(onStartWrite()));
    connect(m_pTcpSocket, SIGNAL(readyRead()), this, SLOT(onGetServerMsg()));
    connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onServerError(QAbstractSocket::SocketError)));
    //
    m_pServerLabel = new QLabel("服务器列表", this);
    m_pServerCmb = new QComboBox(this);
    m_pServerCmb->setMaximumWidth(100);
    m_pServerCmb->insertItem(0, "2#");
    m_pServerCmb->insertItem(1, "3#");
    m_pServerCmb->insertItem(2, "8#");
    connect(m_pServerCmb, SIGNAL(currentIndexChanged(int)), this, SLOT(onSelectServerIP(int)));
    //
    m_pPlayerLabel = new QLabel("玩家名称", this);
    m_pPlayerEdit = new QLineEdit(this);
    m_pPlayerEdit->setMaximumWidth(100);
    connect(m_pPlayerEdit, SIGNAL(textChanged(QString)), this, SLOT(onSetGameName(QString)));
    //
    m_pJoinGameButton = new QPushButton("加入游戏", this);
    m_pJoinGameButton->setMaximumWidth(200);
    m_pJoinGameButton->setMinimumHeight(50);
    connect(m_pJoinGameButton, SIGNAL(clicked()), this, SLOT(onJoinGame()));
    //
    m_pGameDirLabel = new QLabel("设置游戏目录", this);
    m_pGameDirEdit = new QLineEdit(this);
    connect(m_pGameDirEdit, SIGNAL(textChanged(QString)), this, SLOT(onChangeGamePath()));
    m_pGameDirButton = new QPushButton("...", this);
    connect(m_pGameDirButton, SIGNAL(clicked()), this, SLOT(onSetGamePath()));
    m_pGameDirButton->setMaximumWidth(100);
    //
    m_pQuickButton = new QPushButton("快捷键", this);
    m_pQuickButton->setMaximumWidth(100);

    m_pInfoLabel = new QLabel("this");
    m_pInfoLabel->setMinimumWidth(100);
    //
    m_qstrGameServerList.insert(0, "Yd.l4d.cn:27021");
    m_qstrGameServerList.insert(1, "Yd.l4d.cn:27022");
    m_qstrGameServerList.insert(1, "Yd.l4d.cn:27023");
    m_qstrServerIP = m_qstrGameServerList.at(0);
    // 布局:27021
    QGridLayout *pGridLayout = new QGridLayout;
    pGridLayout->addWidget(m_pServerLabel, 0, 0, 1, 1);
    pGridLayout->addWidget(m_pServerCmb, 0, 1, 1, 1);
    pGridLayout->addWidget(m_pPlayerLabel, 1, 0, 1, 1);
    pGridLayout->addWidget(m_pPlayerEdit, 1, 1, 1, 1);
    pGridLayout->addWidget(m_pJoinGameButton, 2, 0, 1, 2);
    pGridLayout->addWidget(m_pGameDirLabel, 3, 0, 1, 1);
    pGridLayout->addWidget(m_pGameDirEdit, 4, 0, 1, 2);
    pGridLayout->addWidget(m_pGameDirButton, 3, 1, 1, 1);
    pGridLayout->addWidget(m_pQuickButton, 5, 0, 1, 2);
    pGridLayout->addWidget(m_pInfoLabel, 0, 2, 6, 1);
    this->setLayout(pGridLayout);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::onSelectServerIP(int iIndex)
{
    m_qstrServerIP = m_qstrGameServerList.at(iIndex);
}

void Dialog::onSetGameName(QString qstrPlayerName)
{
    m_qstrPlayerName = qstrPlayerName;
}

void Dialog::onJoinGame()
{

//    bool bSteamStart = SteamAPI_Init();
//    // 过滤gameaddr"
//    //- Server passes the filter if the server's game address matches the specified IP or IP:port.
//    //gameserveritem_t *pServer = SteamMatchmakingServers()->GetServerDetails( hReq, iServer );

//    CGameServerPing *pGameSer = new CGameServerPing;
//    // 58.221.47.233:27021
//    int32 octet0 = 58, octet1 = 221, octet2 = 47, octet3 = 233;
//    int32 uPort = 27019;
//    uint32 unIPAddress = ( octet3 ) + ( octet2 << 8 ) + ( octet1 << 16 ) + ( octet0 << 24 );
//    pGameSer->RetrieveSteamIDFromGameServer(unIPAddress, uPort);
//   // SteamMatchmakingServers()->PingServer(987574249, 27021, strPingRes);
//    SteamAPI_RunCallbacks();
//    gameserveritem_t server3;
//    pGameSer->ServerResponded(server3);
//    int maxPlayer = server3.m_nMaxPlayers;
//    qDebug() << "ffdd_" << maxPlayer;



//    QHostAddress hostAddr("58.221.47.233");
//    m_pTcpSocket->abort();
//    m_pTcpSocket->connectToHost(hostAddr, 27021);
    // 参数58.221.47.233:27021
    m_qstrArguments.push_back("+name " + m_qstrPlayerName);
    m_qstrArguments.push_back("+connect " + m_qstrServerIP);

    QProcess process_l4d2;
    process_l4d2.startDetached(m_qstrGamePath, m_qstrArguments);
}

void Dialog::onSetGamePath()
{
    QString strDialog = "设置游戏目录";
    QString strDir = "C:\\";
    QString strFileFormat("L4D2 (*.exe)");
    QString strFilePathListTemp = QFileDialog::getOpenFileName(this, strDialog, strDir, strFileFormat);
    if(!strFilePathListTemp.isNull())
    {
        m_qstrGamePath = strFilePathListTemp;
        m_pGameDirEdit->setText(m_qstrGamePath);
    }
}

void Dialog::onChangeGamePath()
{
}

void Dialog::onStartWrite()
{
    QByteArray tstByte = "ip";
    m_pTcpSocket->write(tstByte);
//    if(m_pTcpSocket->waitForConnected())
//    {
//        QHostAddress hostAddr = m_pTcpSocket->localAddress();
//        QString addr = "";
//        if (hostAddr != QHostAddress::Null)
//        {
//          addr = hostAddr.toString();
//        }
//       qDebug() << "client connected";

//    }
    m_pTcpSocket->waitForReadyRead(3000);
}

void Dialog::onGetServerMsg()
{

   // QByteArray getMsg = m_pTcpSocket->readAll();

        if(m_pTcpSocket->waitForReadyRead())
        {
            qDebug() << "good";
            QByteArray getMsg = m_pTcpSocket->readAll();
        }
        else
        {
            qDebug() << "bad";
        }


    int a = 10;
}

void Dialog::onServerError(QAbstractSocket::SocketError socError)
{
    QAbstractSocket::SocketError  sst = socError;

    qDebug() << m_pTcpSocket->errorString();
}
